package handler;

import codec.PacketCodeC;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import packet.AbstractPacket;
import packet.impl.*;
import packet.impl.MessageRequestAbstractPacket;
import packet.impl.MessageResponseAbstractPacket;

import java.util.Date;

/**
 * @author Admin
 */
public class ServerHandler extends ChannelInboundHandlerAdapter {
  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) {
    ByteBuf requestByteBuf = (ByteBuf) msg;

    // 解码
    AbstractPacket packet = PacketCodeC.INSTANCE.decode(requestByteBuf);

    // 判断是否是登陆请求数据包
    if (packet instanceof LoginRequestAbstractPacket) {
      LoginRequestAbstractPacket loginRequestPacket = (LoginRequestAbstractPacket) packet;

      LoginResponseAbstractPacket loginResponsePacket = new LoginResponseAbstractPacket();
      loginResponsePacket.setVersion(packet.getVersion());

      // 登陆校验
      if (valid(loginRequestPacket)) {
        loginResponsePacket.setSuccess(true);
      } else {
        loginResponsePacket.setSuccess(false);
        loginResponsePacket.setReason("账号密码校验错误");
      }

      // 编码
      ByteBuf responseByteBuf = PacketCodeC.INSTANCE.encode(loginResponsePacket);
      ctx.channel().writeAndFlush(responseByteBuf);
    } else if (packet instanceof MessageRequestAbstractPacket) {
      MessageRequestAbstractPacket messageRequestPacket = (MessageRequestAbstractPacket) packet;
      System.out.println(new Date() + ": 收到客户端消息【" + messageRequestPacket.getMessage() + "】");

      MessageResponseAbstractPacket messageResponsePacket = new MessageResponseAbstractPacket();
      messageResponsePacket.setMessage("服务端回复【" + messageRequestPacket.getMessage() + "】");
      ByteBuf responseByteBuf = PacketCodeC.INSTANCE.encode(ctx.alloc(), messageResponsePacket);
      ctx.channel().writeAndFlush(responseByteBuf);
    }
  }

  private boolean valid(LoginRequestAbstractPacket loginRequestPacket) {
    return loginRequestPacket != null;
  }
}
